//
//  NetworkReachability.m
//  OneStoreFramework
//
//  Created by qinqubo on 14/10/4.
//  Copyright (c) 2014年 OneStore. All rights reserved.
//

#import "NetworkReachability.h"
#import "NetworkConfig.h"
#import <CoreCode/CoreCode.h>
#import <AFNetworking/AFNetworking.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

NSString *const NotificationNetworkStatusChange = @"NotificationNetworkStatusChange";

@interface NetworkReachability()

@property (nonatomic, strong) AFNetworkReachabilityManager *manager;
@property (nonatomic, assign) ENetWorkStatus lastNetStatus;

@end

@implementation NetworkReachability

DEF_SINGLETON(NetworkReachability)

- (instancetype)init {
    if (self = [super init]) {
        WEAK_SELF;
        [NSNotificationCenter.defaultCenter addObserverForName:CTRadioAccessTechnologyDidChangeNotification
                                                        object:nil
                                                         queue:[NSOperationQueue mainQueue]
                                                    usingBlock:^(NSNotification *note) {
                                                        STRONG_SELF;
                                                        NSString *status = note.object;
                                                        [self dealWithCT:status];
                                                    }];
        
        [NSNotificationCenter.defaultCenter addObserverForName:AFNetworkingReachabilityDidChangeNotification
                                                        object:nil
                                                         queue:[NSOperationQueue mainQueue]
                                                    usingBlock:^(NSNotification *note) {
             STRONG_SELF;
             NSNumber *item = note.userInfo[AFNetworkingReachabilityNotificationStatusItem];
             AFNetworkReachabilityStatus status = (AFNetworkReachabilityStatus)item.intValue;
             [self dealWithReachabilityStatus:status];
         }];
        
        _manager = [AFNetworkReachabilityManager sharedManager];
        [_manager startMonitoring];
    }
    return self;
}

- (void)setCurrentNetStatus:(ENetWorkStatus)currentNetStatus {
    if (_currentNetStatus != currentNetStatus) {
        _currentNetStatus = currentNetStatus;
        
        //网络类型
        switch (currentNetStatus) {
            case kConnectTo2G:
                [NetworkConfig sharedInstance].nettype = @"2g";
                break;
            case kConnectTo3G:
                [NetworkConfig sharedInstance].nettype = @"3g";
                break;
            case kConnectTo4G:
                [NetworkConfig sharedInstance].nettype = @"4g";
                break;
            case kConnectToWifi:
                [NetworkConfig sharedInstance].nettype = @"wifi";
                break;
            case kConnectToWWAN:
                //do nothing
                break;
            default:
                [NetworkConfig sharedInstance].nettype = @"";
                break;
        }
    }
}

- (void)dealloc {
    [self.manager stopMonitoring];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/**
 *  功能:获取网络连接状况
 */
- (void)generateNetStatus {
    CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
    [self dealWithCT:telephonyInfo.currentRadioAccessTechnology];
}

- (void)dealWithCT:(NSString *)status {
    PBLog(@"New Radio Access Technology: %@", status);
    if ([status isEqualToString:CTRadioAccessTechnologyGPRS] ||
        [status isEqualToString:CTRadioAccessTechnologyEdge]) {//2g,2.5g
        self.currentNetStatus = kConnectTo2G;
    } else if ([status isEqualToString:CTRadioAccessTechnologyWCDMA] ||
             [status isEqualToString:CTRadioAccessTechnologyHSDPA] ||
             [status isEqualToString:CTRadioAccessTechnologyHSUPA] ||
             [status isEqualToString:CTRadioAccessTechnologyCDMA1x] ||
             [status isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
             [status isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
             [status isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
             [status isEqualToString:CTRadioAccessTechnologyeHRPD]) {//3g
        self.currentNetStatus = kConnectTo3G;
    } else if ([status isEqualToString:CTRadioAccessTechnologyLTE]){//4g
        self.currentNetStatus = kConnectTo4G;
    } else {
        self.currentNetStatus = kConnectToNull;
    }
    
    [self dealWithReachabilityStatus:self.manager.networkReachabilityStatus];
}

- (void)dealWithReachabilityStatus:(AFNetworkReachabilityStatus)status {
    switch (status) {
        case AFNetworkReachabilityStatusNotReachable:
            PBLog(@"NotReachable notify recieved!");
            self.currentNetStatus = kConnectToNull;
            break;
        case AFNetworkReachabilityStatusReachableViaWWAN:
            PBLog(@"ReachableViaWWAN notify recieved!");
                self.currentNetStatus = kConnectToWWAN;
            break;
        case AFNetworkReachabilityStatusReachableViaWiFi:
            PBLog(@"ReachableViaWiFi notify recieved!");
            self.currentNetStatus = kConnectToWifi;
            break;
        default: {
            break;
        }
    }
  
    if (self.lastNetStatus != self.currentNetStatus) {
        self.lastNetStatus = self.currentNetStatus;
        
        //网络状态变更 发送通知
        dispatch_async(dispatch_get_main_queue(), ^{
            @try {
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationNetworkStatusChange object:nil userInfo:nil];
            }
            @catch (NSException *exception) {}
            @finally {}
        });
        
    }
}

- (BOOL)isConnectedToNet {
    return (self.currentNetStatus & kConnectToAny);
}

@end
